package top.codedance.iotp.server.net.thrid.user;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import top.codedance.iotp.common.entity.UserEntity;
import top.codedance.iotp.common.util.HttpRequestUtil;
import top.codedance.iotp.server.net.thrid.UserThrid;

import java.util.ArrayList;
import java.util.List;

public class ChongQingUserImpl implements UserThrid {
    private final String BASE_URL = "http://127.0.0.1/iotp/api";
    public boolean isExits(UserEntity userEntity) {
        JSONObject post = HttpRequestUtil.post(BASE_URL + "/user/check", JSON.toJSONString(userEntity));
        if(post.getInteger("status") == 200){
            return post.getBoolean("data");
        }else{
            return false;
        }
    }

    public boolean isExitsOfAdmin(UserEntity userEntity) {
        JSONObject post = HttpRequestUtil.post(BASE_URL + "/admin/check", JSON.toJSONString(userEntity));
        if(post.getInteger("status") == 200){
            return post.getBoolean("data");
        }else{
            return false;
        }
    }

    public void add(UserEntity userEntity) {
        HttpRequestUtil.post(BASE_URL + "/user/add", JSON.toJSONString(userEntity));
    }

    public List<UserEntity> list() {
        List<UserEntity> list = new ArrayList<UserEntity>();
        JSONObject post = HttpRequestUtil.post(BASE_URL + "/user/list", null);
        if(post.getInteger("status") == 200){
            JSONArray data = post.getJSONArray("data");
            for(int i = 0;i < data.size();i++){
                JSONObject jsonObject = data.getJSONObject(i);
                UserEntity userEntity = new UserEntity();
                userEntity.setId(jsonObject.getInteger("id"));
                userEntity.setUsername(jsonObject.getString("username"));
                userEntity.setPassword(jsonObject.getString("password"));
                userEntity.setDeviceId(jsonObject.getString("deviceId"));
                list.add(userEntity);
            }
        }
        return list;
    }

    public void delete(int id) {
        UserEntity userEntity = new UserEntity();
        userEntity.setId(id);
        HttpRequestUtil.post(BASE_URL + "/user/delete", JSON.toJSONString(userEntity));
    }
}
